import userApi from "./api/chaoxing/userApi/index";
import dbUserApi from "./api/wechatCloud/dbUserApi/index";
import showToast from "./utils/toast";

wx.cloud.init({
  env: 'sleep-sign-0g9xr6lm95e07431'
})
/**
 * 
 * @param next 这个方法放行`
 */
const routerBeforeEach = async (next: Function) => {
  let token = userApi.getUser(getApp().globalData.curUser);
  if (token) {
    // 登录成功
    next()
    return;
  }
  await new Promise((resolve,reject) => {
    wx.login({
      async success(res){
        const config = await dbUserApi.getConfigByParma({_openid:res.code})
        if (config && config.data && config.data[0] && config.data[0].name && config.data[0]._id && config.data[0].password){
          let {_id,password,name} = config.data[0]
           const loginRes = await userApi.userLogin(_id,password, false);
           if (typeof loginRes == "string"){
             reject("登录失败")
             return;
           }
           showToast({title:"登录成功",icon:"none"})
           userApi.storeUser(_id, loginRes);
           getApp().globalData.curUser = _id
           userApi.storeUserName(name);
           resolve("ok");
        }else {
        resolve("ok")
        }
      }
    })
  }).catch(e=>{
    showToast({title:e,icon:"error"})
  })
  token = userApi.getUser(getApp().globalData.curUser);
  if (token){
    next()
    return;
  }
  const pages = getCurrentPages()
  const curPage = pages[pages.length - 1]
  if (curPage.route != 'pages/login/login') {
    wx.navigateTo({
      url: '/pages/login/login'
    })
    return;
  }
  next()
}
const OldPage = Page;
Page = function (options) {
  const oldShow = options.onShow
  options.onShow = function () {
    routerBeforeEach(() => {
      oldShow?.apply(this, arguments as any)
    })
  }
  OldPage(options)
}
App<IAppOption>({
  globalData: {
    curUser: '',
  },
  async onLaunch(){
    // wx.login({
    //   async success(res){
    //     const config = await dbUserApi.getConfigByParma({_openid:res.code})
    //     if (config && config.data && config.data[0] && config.data[0]._id && config.data[0].password){
    //       let {_id,password} = config.data[0]
    //        const loginRes = await userApi.userLogin(_id,password, false);
    //        if (typeof loginRes == "string"){
    //          showToast({title:"自动登录失败,请手动登录",icon:"none"})
    //          return;
    //        }
    //        showToast({title:"登录成功",icon:"none"})
    //        userApi.storeUser(_id, loginRes);
    //        getApp().globalData.curUser = _id
    //     }
    //   }
    // })
  }
})